import H5ClientDef from '@/h5sdk/BakiClientDef.js';
import BakiDef from '@/h5sdk/BakiDef.js';
export default function H5Client(onConnect, onDisconnect, onLogin, onOpenStream, onCloseStream, onStream, ctx){
    this.onConnect = onConnect;
    this.onDisconnect = onDisconnect;
    this.onLogin = onLogin;
    this.onOpenStream = onOpenStream;
    this.onCloseStream = onCloseStream;
    this.onStream = onStream;
    this.ctx = ctx;

    this.devId = "";
    this.devPwd = "";
    this.connected = false;
    this.p2p_sock = null;
    this.media_sock = null;
    this.ckey = Math.floor(Math.random() * 100000000) + 10000000;
    this.sid = this.ckey + 2;
    this.dkey = this.ckey + 4;
    this.seq = 1;

    var that = this;

    var handleConnectMedia = function(data){
				that.media_sock = uni.connectSocket({
					url: "ws://78.189.93.133:18088/index.html?key=" + that.ckey + "&deviceId=" + that.devId + "&sid=" + that.sid + "&liveinterval=10&livetimes=3&version=1&type=client"
				});
        // that.media_sock = new WebSocket("ws://78.189.93.133:18088/index.html?key=" + that.ckey + "&deviceId=" + that.devId + "&sid=" + that.sid + "&liveinterval=10&livetimes=3&version=1&type=client");
        console.log(that.media_sock);
				that.media_sock.onOpen(() => {
				  that.media_sock.binaryType = "arraybuffer";
				  
				  var iot_data = BakiDef.build_open(that.sid, that.devId);
				  var data = BakiDef.build_head(BakiDef.BAKI_MSGID_MEDIA_OPEN, that.sid, that.ckey, that.dkey, iot_data);
				  that.media_sock.send(
					{
						data: data
					});
				  
				  //请求超时判断
				  that.media_time = Date.parse(new Date());
				  that.media_req_timer = setInterval(function(){
				  // 处理请求p2psever,turnsever 超时处理
				  var time = Date.parse(new Date());
				  // 毫秒/1000
				  var time_out = (time - that.media_time) /1000;
				  console.log(time_out);
				  if (time_out >= 10) {
				      //超时关闭
				      that.media_sock.close();
				  }}, 1000);  
				});
				
				that.media_sock.onMessage((res) => {
					console.log('0000000000000000000')
				  var data = new Uint8Array(event.data);
				      var head = BakiDef.parse_head(data); 
				      console.log(head);
				      if(head.messageId == BakiDef.BAKI_MSGID_MEDIA_OPEN_RES){
								console.log('1111111111111111')
				          //打开媒体通道成功，
				          if(head.status == BakiDef.BAKI_MSG_STATUS_SUCCESS){
				              var res = BakiDef.parse_open(data.slice(BakiDef.headSize));
				              console.log(res);                  
				          }
				          else{
				              that.media_sock.close();
				          }
				          that.onConnect(that.ctx, head.status);
				          if(that.media_req_timer > 0){
				              clearInterval(that.media_req_timer);
				              that.media_req_timer = 0;
				          }                  
				      }
				      else if(head.messageId == BakiDef.BAKI_MSGID_DATA){
								console.log('22222222222222')
				          //收到数据，解析出数据结构
				          var res = H5ClientDef.parse_head(data.slice(BakiDef.headSize));
				          console.log(res);
				          if(res.chn == H5ClientDef.Cmd_Channel.CMD_CHN){
				              //命令数据
				              if(res.cmdType == H5ClientDef.Cmd_Type.IOCTRL_DEV_LOGIN_RESP){
				                  //登录返回
				                  var login_res = H5ClientDef.parse_login_res(data.slice(BakiDef.headSize + H5ClientDef.Cmd_Head_Size));
				                  that.onLogin(that.ctx, login_res);
				              }
				              else if(res.cmdType == H5ClientDef.Cmd_Type.IOCTRL_TYPE_LIVE_START_RESP){
				                  //开启流返回
				                  var openStream_res = H5ClientDef.parse_open_stream_res(data.slice(BakiDef.headSize + H5ClientDef.Cmd_Head_Size));
				                  that.onOpenStream(that.ctx, openStream_res);
				              }
				              else if(res.cmdType == H5ClientDef.Cmd_Type.IOCTRL_TYPE_LIVE_STOP_RESP){
				                  //关闭流返回
				                  var closeStream_res = H5ClientDef.parse_close_stream_res(data.slice(BakiDef.headSize + H5ClientDef.Cmd_Head_Size));
				                  that.onCloseStream(that.ctx, closeStream_res);
				              }
				          }
				          else{
				              //媒体数据
				              var media_data = data.slice(H5ClientDef.Media_Head_Size);
				              that.onStream(that.ctx, that.devId, media_data, res.frameType, res.pts);
				          }
				      }
				  
				});
				 
				// 监听连接关闭
				that.media_sock.onClose(() => {
				  //关闭超时判断
				  if (that.media_req_timer > 0) {
				      console.log("close time out timer");
				      clearInterval(that.media_req_timer);
				      that.media_req_timer = 0;
				  }          
				  that.onDisconnect(that.ctx, that.devId);
				});
				 
				// 监听错误
				that.media_sock.onError((err) => {
				  console.log("error", err);  
				});
        // that.media_sock.addEventListener("open", function(event){
        //     console.log("open", event);
        //     that.media_sock.binaryType = "arraybuffer";

        //     var iot_data = BakiDef.build_open(that.sid, that.devId);
        //     var data = BakiDef.build_head(BakiDef.BAKI_MSGID_MEDIA_OPEN, that.sid, that.ckey, that.dkey, iot_data);
        //     that.media_sock.send(data);

        //     //请求超时判断
        //     that.media_time = Date.parse(new Date());
        //     that.media_req_timer = setInterval(function(){
        //     // 处理请求p2psever,turnsever 超时处理
        //     var time = Date.parse(new Date());
        //     // 毫秒/1000
        //     var time_out = (time - that.media_time) /1000;
        //     console.log(time_out);
        //     if (time_out >= 10) {
        //         //超时关闭
        //         that.media_sock.close();
        //     }}, 1000);            
        // });

        // that.media_sock.addEventListener("message", function(event){
        //     var data = new Uint8Array(event.data);
        //     var head = BakiDef.parse_head(data); 
        //     console.log(head);
        //     if(head.messageId == BakiDef.BAKI_MSGID_MEDIA_OPEN_RES){
        //         //打开媒体通道成功，
        //         if(head.status == BakiDef.BAKI_MSG_STATUS_SUCCESS){
        //             var res = BakiDef.parse_open(data.slice(BakiDef.headSize));
        //             console.log(res);                  
        //         }
        //         else{
        //             that.media_sock.close();
        //         }
        //         that.onConnect(that.ctx, head.status);
        //         if(that.media_req_timer > 0){
        //             clearInterval(that.media_req_timer);
        //             that.media_req_timer = 0;
        //         }                  
        //     }
        //     else if(head.messageId == BakiDef.BAKI_MSGID_DATA){
        //         //收到数据，解析出数据结构
        //         var res = H5ClientDef.parse_head(data.slice(BakiDef.headSize));
        //         console.log(res);
        //         if(res.chn == H5ClientDef.Cmd_Channel.CMD_CHN){
        //             //命令数据
        //             if(res.cmdType == H5ClientDef.Cmd_Type.IOCTRL_DEV_LOGIN_RESP){
        //                 //登录返回
        //                 var login_res = H5ClientDef.parse_login_res(data.slice(BakiDef.headSize + H5ClientDef.Cmd_Head_Size));
        //                 that.onLogin(that.ctx, login_res);
        //             }
        //             else if(res.cmdType == H5ClientDef.Cmd_Type.IOCTRL_TYPE_LIVE_START_RESP){
        //                 //开启流返回
        //                 var openStream_res = H5ClientDef.parse_open_stream_res(data.slice(BakiDef.headSize + H5ClientDef.Cmd_Head_Size));
        //                 that.onOpenStream(that.ctx, openStream_res);
        //             }
        //             else if(res.cmdType == H5ClientDef.Cmd_Type.IOCTRL_TYPE_LIVE_STOP_RESP){
        //                 //关闭流返回
        //                 var closeStream_res = H5ClientDef.parse_close_stream_res(data.slice(BakiDef.headSize + H5ClientDef.Cmd_Head_Size));
        //                 that.onCloseStream(that.ctx, closeStream_res);
        //             }
        //         }
        //         else{
        //             //媒体数据
        //             var media_data = data.slice(H5ClientDef.Media_Head_Size);
        //             that.onStream(that.ctx, that.devId, media_data, res.frameType, res.pts);
        //         }
        //     }
        // });

        // that.media_sock.addEventListener("close", function(event){
        //     //关闭超时判断
        //     if (that.media_req_timer > 0) {
        //         console.log("close time out timer");
        //         clearInterval(that.media_req_timer);
        //         that.media_req_timer = 0;
        //     }          
        //     that.onDisconnect(that.ctx, that.devId);
        // })

        // that.media_sock.addEventListener("error", function(event){
        //     console.log("error", event);            
        // })
    }

    var connectToDevice = function(devId){
        //寻址过程暂略
        that.devId = devId;
        that.dkey = parseInt(that.devId);
				that.p2p_sock = uni.connectSocket({
					url: "ws://78.189.93.133:8088/index.html?key=" + that.ckey + "&deviceId=" + devId + "&sid=" + that.sid + "&liveinterval=10&livetimes=3&version=1&type=client",
					success:()=>{
						console.log('open')
					}
				
				});
        // that.p2p_sock = new WebSocket("ws://78.189.93.133:8088/index.html?key=" + that.ckey + "&deviceId=" + devId + "&sid=" + that.sid + "&liveinterval=10&livetimes=3&version=1&type=client");
        console.log(that.p2p_sock);
				that.p2p_sock.onOpen((event) => {
						console.log("open", event);
            that.p2p_sock.binaryType = "arraybuffer";

            var iot_data = BakiDef.build_open(that.sid, that.devId);
            var data = BakiDef.build_head(BakiDef.BAKI_MSGID_P2P_OPEN, that.sid, that.ckey, that.dkey, iot_data);
            that.p2p_sock.send(
						{
						    data: data
						  });

            //请求超时判断
            that.time = Date.parse(new Date());
            that.req_timer = setInterval(function(){
            // 处理请求p2psever,turnsever 超时处理
            var time = Date.parse(new Date());
            // 毫秒/1000
            var time_out = (time - that.time) /1000;
            console.log(time_out);
            if (time_out >= 10) {
                //超时关闭
                that.p2p_sock.close();
            }}, 1000); 
				});
				

        that.p2p_sock.onMessage((event)=>{
            var data = new Uint8Array(event.data);
            var head = BakiDef.parse_head(data); 
            console.log(head);
            if(head.messageId == BakiDef.BAKI_MSGID_P2P_OPEN_RES){
							console.log(head.status)
                //打开P2P通道成功，发起转发请求
                if(head.status == BakiDef.BAKI_MSG_STATUS_SUCCESS){
                    var iot_data = BakiDef.build_connect_request(that.devId,that.ckey, that.sid, that.dkey, "", 0, "", 0);
                    var data = BakiDef.build_head(BakiDef.BAKI_MSGID_CONNECT_REQUEST, that.sid, that.devId, that.ckey, iot_data);
                    that.p2p_sock.send(
										{
										    data: data
										  });
                    if(that.req_timer > 0){
                        clearInterval(that.req_timer);
                        that.req_timer = 0;
                    }
                }
                else{
                    that.onConnect(that.ctx, head.status);
                    that.p2p_sock.close();
                }
            }
            else if(head.messageId == BakiDef.BAKI_MSGID_CONNECT_RESPONSE){
							console.log(555555555555)
                //收到转发请求，开始连接转发服务器
                var res_data = data.slice(BakiDef.headSize);
                var res = BakiDef.parse_connect_response(res_data);
                handleConnectMedia(res);
            }
        });

        that.p2p_sock.onClose((event)=>{
            //关闭超时判断
            if (that.req_timer > 0) {
                console.log("close time out timer");
                clearInterval(that.req_timer);
                that.req_timer = 0;
            }          
        })

        that.p2p_sock.onError((event)=>{
            console.log("error", event);
        })
    
		}    
    
    this.connect = function(devId){
        that.devId = devId;
        connectToDevice(devId);
    }

    this.disConnect = function(){
        if(that.media_sock){
            that.media_sock.close();
        }
        if(that.p2p_sock){
            that.p2p_sock.close();
        }
    }

    this.login = function(devPwd){
        if(that.media_sock){
            var data = H5ClientDef.build_login(devPwd);
            var api_data = H5ClientDef.build_cmd_head(H5ClientDef.Cmd_Type.IOCTRL_DEV_LOGIN_REQ, that.seq, data);
            that.seq++;
            var iot_data = BakiDef.build_head(BakiDef.BAKI_MSGID_DATA, that.sid, that.ckey, that.dkey, api_data);
            console.log("login size ", iot_data.length);
            that.media_sock.send({
							data:iot_data
						});
        }
    }

    this.openStream = function(){
        if(that.media_sock){
            var data = H5ClientDef.build_open_stream();
            var api_data = H5ClientDef.build_cmd_head(H5ClientDef.Cmd_Type.IOCTRL_TYPE_LIVE_START_REQ, that.seq, data);
            that.seq++;
            var iot_data = BakiDef.build_head(BakiDef.BAKI_MSGID_DATA, that.sid, that.ckey, that.dkey, api_data);
            console.log("openStream size ", iot_data.length);
            that.media_sock.send({
            	data:iot_data
            });
        }
    }

    this.closeStream = function(){
        if(that.media_sock){
            var data = H5ClientDef.build_close_stream();
            var api_data = H5ClientDef.build_head(H5ClientDef.Cmd_Type.IOCTRL_TYPE_LIVE_STOP_REQ, that.seq, data);
            that.seq++;
            var iot_data = BakiDef.build_cmd_head(BakiDef.BAKI_MSGID_DATA, that.sid, that.ckey, that.dkey, api_data);
            that.media_sock.send({
            	data:iot_data
            });
        }
    }

    this.sendIOCtrl = function(data){
        if(that.media_sock){
            that.media_sock.send({
            	data:iot_data
            });
        }
    }
}